package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.WantdeliverDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by zjx on 2018
 */

public class MyselfjijianActivity extends AppCompatActivity {
    private int pagenow = 1;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    private int currentlastitem = 0;
    private boolean lastloading = false;
    public LinearLayoutManager lm;
    private RcylcerAdater adpter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.initStatus(this, R.color.black);
        setContentView(R.layout.activity_myselfjijian);
        ButterKnife.bind(this);
        initComponent();
    }
    public  void initComponent(){
        this.lm = new LinearLayoutManager(this, 1, false);
        this.recyclerview.setLayoutManager(this.lm);
        List<WantdeliverDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setAdapter(new RcylcerAdater(this,dataBeans));
        this.pulltofresh.setPullDownEnable(true);
        this.pulltofresh.setPullUpEnable(true);
        this.pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                       pagenow=1;
                       query();
            }
            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                append(pagenow);
            }
        });
        this.pulltofresh.autoRefresh();
    }
    @OnClick(value = {R.id.backbt})
    public void onMyClick(View view){
         switch (view.getId()){
             case R.id.backbt:
                 finish();
                 break;
         }
    }


  public class RcylcerAdater extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
      public List<WantdeliverDomain.DataBean> dataBeen;
      public LayoutInflater inflater;
        public RcylcerAdater(Context context, List<WantdeliverDomain.DataBean> dataBeans){
           this.dataBeen=dataBeans;
           inflater=LayoutInflater.from(context);
         }

      @Override
      public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

             return new IndexHoler(inflater.inflate(R.layout.layout_myselfjijian_listitem,parent,false));
      }

      @Override
      public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final IndexHoler  paramViewHolder = (IndexHoler)holder;
          final WantdeliverDomain.DataBean localDataBean = (WantdeliverDomain.DataBean)this.dataBeen.get(position);
          Glide.with(MyselfjijianActivity.this)
                  .load(localDataBean.getUserAvatarpath())
                  .asBitmap()
                  .centerCrop()
                  .animate(R.anim.fade_in)
                  .placeholder(R.drawable.nim_avatar_default)
                  .into(new SimpleTarget<Bitmap>() {
                      @Override
                      public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                          paramViewHolder.cir_icon.setImageBitmap(resource);
                      }
                  });
          paramViewHolder.realname_name.setText("寄货人：" + localDataBean.getUserRealname());
          paramViewHolder.iphone.setText("联系方式：" + localDataBean.getUserIphone());
          paramViewHolder.from_address.setText("寄货人地址：" + localDataBean.getFromProvince() + localDataBean.getFromCity() + localDataBean.getFromArea() + localDataBean.getFromAddress());
          paramViewHolder.to_address.setText("收货人地址：" + localDataBean.getToProvince() + localDataBean.getToCity() + localDataBean.getToArea() + localDataBean.getToAddress());
          paramViewHolder.readby_bt.setOnClickListener(new View.OnClickListener()
          {
              public void onClick(View paramAnonymousView)
              {
                  updatestate(localDataBean.getWantdeliverId(), 2);
                  delete(position);
              }
          });
          paramViewHolder.close_bt.setOnClickListener(new View.OnClickListener()
          {
              public void onClick(View paramAnonymousView)
              {
                   updatestate(localDataBean.getWantdeliverId(), 3);
                      delete(position);
              }
          });
      }

      @Override
      public int getItemCount() {
          return dataBeen.size();
      }
      public void initAppend(List<WantdeliverDomain.DataBean> paramList)
      {
          this.dataBeen.addAll(paramList);
          notifyDataSetChanged();
      }

      public void initRefresh(List<WantdeliverDomain.DataBean> paramList)
      {
          this.dataBeen.removeAll(this.dataBeen);
          this.dataBeen.addAll(paramList);
          notifyDataSetChanged();
      }
      public class IndexHoler extends RecyclerView.ViewHolder {
          public CircleImageView cir_icon;
          public Button close_bt;
          public TextView from_address;
          public TextView iphone;
          public Button readby_bt;
          public TextView realname_name;
          public View rootView;
          public TextView to_address;

          public IndexHoler(View itemView) {
              super(itemView);
              this.rootView = itemView;
              this.cir_icon = itemView.findViewById(R.id.cir_icon);
              this.realname_name = itemView.findViewById(R.id.realname_name);
              this.iphone = itemView.findViewById(R.id.iphone);
              this.from_address = itemView.findViewById(R.id.from_address);
              this.to_address =itemView.findViewById(R.id.to_address);
              this.readby_bt =itemView.findViewById(R.id.readby_bt);
              this.close_bt =itemView.findViewById(R.id.close_bt);
          }





      }
      public void delete(int paramInt)
      {
          this.dataBeen.remove(paramInt);
          notifyDataSetChanged();
      }
  }




    public void query() {
        List localList = Xutils.queryAll(getApplication(), User.class);
        if ((localList == null) || (localList.size() == 0)) {
            return;
        }
        HashMap localHashMap = new HashMap();
        localHashMap.put("pagenow", this.pagenow + "");
        localHashMap.put("userId", "" + ((User) localList.get(0)).getUserId());
        localHashMap.put("state", "0");
        Xutils.POST(HttpUrl.mywantdeliverfenyequerystate, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyselfjijianActivity.this.pulltofresh.refreshFinish(0);
                Gson gson = new Gson();
                WantdeliverDomain domain = gson.fromJson(result, WantdeliverDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (MyselfjijianActivity.this.adpter == null) {
                                recyclerview.setAdapter(new RcylcerAdater(MyselfjijianActivity.this,domain.getData()));
                            } else {
                              adpter.initRefresh(domain.getData());
                            }
                        }

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyselfjijianActivity.this.pulltofresh.refreshFinish(1);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void append(int pagenow) {
        List localList = Xutils.queryAll(getApplication(), User.class);
        if ((localList == null) || (localList.size() == 0)) {
            return;
        }
        HashMap localHashMap = new HashMap();
        localHashMap.put("pagenow", this.pagenow + "");
        localHashMap.put("userId", "" + ((User) localList.get(0)).getUserId());
        localHashMap.put("state", "0");
        Xutils.POST(HttpUrl.mywantdeliverfenyequerystate, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyselfjijianActivity.this.pulltofresh.loadmoreFinish(0);
                Gson gson = new Gson();
                WantdeliverDomain domain = gson.fromJson(result, WantdeliverDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (MyselfjijianActivity.this.adpter == null) {
                                recyclerview.setAdapter(new RcylcerAdater(MyselfjijianActivity.this,domain.getData()));
                            } else {
                                adpter.initAppend(domain.getData());
                            }
                        }

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading=false;
                MyselfjijianActivity.this.pulltofresh.loadmoreFinish(1);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void updatestate(int wantdeliverId, int state) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("state", "" + state);
        localHashMap.put("wantdeliverId", wantdeliverId + "");
        Xutils.POST(HttpUrl.mywantdeliverupdatestate, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("****************************onSuccess*"+result);
                try {
                    JSONObject object=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),object.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (object.getInt("state")){
                        case HttpCode.SUCCESS:

                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }



}
